<template>
    <div :class="['section-wrap', flag ? 'flag' : '']" ref="versionItemRef">
        <!-- 折叠 -->
        <a-collapse v-model:activeKey="activeKey" :bordered="false" v-if="collapse" @change="handleChange">
            <template #expandIcon="{ isActive }">
                <CaretDownOutlined v-if="isActive" />
                <CaretRightOutlined v-else />
            </template>
            <a-collapse-panel key="1" :style="customStyle">
                <template #header>
                    <flexbox style="width: 100%; font-size: 14px">
                        <flexbox style="flex: 1; overflow: hidden">
                            <span class="font-w-b" style="flex-shrink: 0">{{ detail.versionNumber.toString() }}</span>
                            <div style="flex-shrink: 0; margin-left: 12px; color: #505a6e">
                                <h-status-badge :status="detail.status" type="version" />
                            </div>
                            <div style="margin-left: 12px; color: #505a6e; overflow: hidden" v-if="detail.startTime">
                                <HToolTip :title="rangeTime">
                                    <span>{{ rangeTime }}</span>
                                </HToolTip>
                            </div>
                            <div class="pro-num-wrap" style="flex-shrink: 0" v-if="detail.pmpProductRequires">
                                <div
                                    style="
                                        width: 16px;
                                        height: 16px;
                                        display: flex;
                                        justify-content: center;
                                        align-items: center;
                                        border-radius: 50%;
                                        background: rgba(4, 120, 211, 0.15);
                                    "
                                >
                                    <span style="font-size: 12px; line-height: 12px; font-weight: 600; color: #107ed5">
                                        {{ detail.pmpProductRequires.length }}
                                    </span>
                                </div>
                                <span class="title">产品需求</span>
                            </div>
                        </flexbox>
                        <div style="flex-shrink: 0">
                            <flexbox justify="center" class="btn-cont" @click.stop="showDetail" v-if="detail.status == 1">
                                <my-icon type="iconfaqi" />
                                <span style="margin-left: 5px">发起流程</span>
                            </flexbox>
                            <flexbox justify="center" class="btn-cont" @click="showDetail" v-else>
                                <my-icon type="iconxingzhuangjiehe2" />
                                <span style="margin-left: 5px">查看详情</span>
                            </flexbox>
                        </div>
                    </flexbox>
                </template>
                <div ref="requireListRef" class="list-wrap">
                    <div
                        class="workbench-require-card-item"
                        style="cursor: pointer"
                        v-for="item of detail.pmpProductRequires"
                        :key="item.id"
                        @click.stop="showProDetail(item.id)"
                    >
                        <flexbox>
                            <flexbox style="flex: 1; overflow: hidden">
                                <div style="flex-shrink: 0; margin-left: 4px; width: 16px">
                                    <div class="show-icon">
                                        <my-icon type="icondrag" />
                                    </div>
                                </div>
                                <a-tag style="flex-shrink: 0; border-radius: 12px; background: #fff" v-if="item.level">
                                    <h-level :level="item.level" />
                                </a-tag>
                                <h-product-type :type="$filters.valToNameFilter('requireType', item.requireType)" style="flex-shrink: 0" />
                                <HToolTip :title="item.requireName">
                                    <span style="color: #172b4d; margin-left: 4px">{{ item.requireName }}</span>
                                </HToolTip>
                            </flexbox>
                            <div
                                @click.stop="handleDelete(item.id)"
                                style="
                                    display: flex;
                                    justify-content: center;
                                    align-items: center;
                                    width: 40px;
                                    height: 22px;
                                    margin-right: 12px;
                                    cursor: pointer;
                                "
                            >
                                移除
                            </div>
                        </flexbox>
                    </div>
                </div>
                <template #extra>
                    <slot name="titleExtra" />
                </template>
            </a-collapse-panel>
        </a-collapse>
        <!-- 不折叠 -->
        <div class="section-cont" v-else>
            <flexbox align="center" class="section-header">
                <div class="section-header-title">
                    <span v-if="title">
                        {{ title }}
                    </span>
                    <slot name="title" v-else />
                </div>
                <div class="section-header-action">
                    <slot name="titleExtra" />
                </div>
            </flexbox>
            <slot />
        </div>

        <OpinionModal ref="OpinionModalRef" @success="handleOpinionModalSuccess" />
    </div>
</template>

<script lang="ts">
import moment from 'moment';
import store from '@/store';
import api from '@/api';
import { message } from 'ant-design-vue';
import { useRouter } from 'vue-router';
import { useDrop } from '@/hooks/content/useDrop';
import OpinionModal from './components/OpinionModal.vue';
import HToolTip from '@/components/HToolTip/index.vue';
import { productTableColumns } from './config/columns';
import { HStatusBadge, HLevel, HProductType } from '@/components';
import { defineComponent, onMounted, ref, unref, nextTick, computed, reactive, toRefs, getCurrentInstance } from 'vue';
import { CaretRightOutlined, CaretDownOutlined } from '@ant-design/icons-vue';
export default defineComponent({
    components: {
        CaretRightOutlined,
        CaretDownOutlined,
        HStatusBadge,
        HToolTip,
        HLevel,
        HProductType,
        OpinionModal
    },
    props: {
        detail: {
            type: Object,
            default: () => ({})
        },
        collapse: {
            type: Boolean,
            default: true
        },
        defaultOpen: {
            type: Boolean,
            default: false
        }
    },
    emits: ['change', 'success'],
    setup(props, { emit }) {
        const instance: any = getCurrentInstance();
        const router = useRouter();
        const versionItemRef = ref<any>(null);
        const requireListRef = ref<any>(null);
        const OpinionModalRef = ref<any>(null);
        const activeKey = ref(['1']);
        const state = reactive<any>({
            lastenter: null,
            flag: false,
            processStepStatus: '',
            currRequireId: ''
        });
        const rangeTime = computed(() => {
            const startTime = props.detail.randdPlanStartTime ? moment(props.detail.randdPlanStartTime).format('YYYY-MM-DD') : '';
            const expectTime = props.detail.expectTime ? moment(props.detail.expectTime).format('YYYY-MM-DD') : '';
            return expectTime ? `${startTime}~${expectTime}` : `${startTime}`;
        });
        const customStyle = 'background: #fff;overflow: hidden;border:0;font-size: 16px; color: #1f2329;';
        activeKey.value = props.defaultOpen ? ['1'] : ['0'];
        const handleChange = (val) => {
            emit('change', val);
        };
        const handleDelete = async (id) => {
            state.currRequireId = id;
            if (!state.processStepStatus) {
                await getProcessStatus();
            }
            if (props.detail.pmpProductRequires.length === 1 && state.processStepStatus === 'requireOnline') {
                message.warn('这是该版本唯一的需求，不可移除');
                return;
            }
            if (+props.detail.processStatus >= 3) {
                unref(OpinionModalRef).open();
            } else {
                handleRemoveRequire();
            }
        };
        const handleOpinionModalSuccess = async (changeOpinion) => {
            state.changeOpinion = changeOpinion;
            handleRemoveRequire();
        };
        const handleRemoveRequire = async () => {
            if (!state.processStepStatus) {
                await getProcessStatus();
            }
            const { empId, name } = store.getters.userInfo.employeeDTO;
            const { id, versionName, versionNumber } = props.detail;
            const query = [
                {
                    productRequireId: state.currRequireId,
                    relateVersionId: id,
                    relateVersionName: versionName,
                    relateVersionNumber: versionNumber,
                    status: 'delete',
                    empId,
                    empName: name,
                    processStatus: props.detail.processStatus,
                    taskNode: state.processStepStatus,
                    changeOpinion: state.changeOpinion,
                    record: ['3', '4', '5', '6', '7', '8', '9'].includes(props.detail.processStatus) // 789(验收，上线审核和上线流程)需要记录需求列表操作
                }
            ];
            const { success, errorMsg } = await api.productRequireModel.batchDeal(query);
            if (success) {
                message.success('移除成功');
                state.currRequireId = '';
                emit('success', props.detail);
                // 刷新产品需求列表，因为解除完，已排期会变成未排期
                instance.proxy.$mitt.emit('refreshList', {}, true);
                // 刷新业务需求，因为绑定完，待排期会变成进行中
                instance.proxy.$mitt.emit('refreshTaskList', {}, true);
            } else {
                message.error(errorMsg);
            }
        };
        const handleUpdateBatch = async (saveQuery = {}) => {
            const { empId, name } = store.getters.userInfo.employeeDTO;
            const { id, versionName, versionNumber } = props.detail;
            const item = store.getters.moveData;
            const query = [
                {
                    productRequireId: item.id,
                    relateVersionId: id,
                    relateVersionName: versionName,
                    relateVersionNumber: versionNumber,
                    status: 'add',
                    empId,
                    empName: name,
                    ...saveQuery
                }
            ];
            const { success, errorMsg } = await api.productRequireModel.batchDeal(query);
            if (success) {
                message.success('绑定成功');
                emit('success', props.detail);
                // 刷新产品需求列表，因为绑定完，未排期会变成已排期
                instance.proxy.$mitt.emit('refreshList', {}, true);
                // 刷新业务需求，因为绑定完，待排期会变成进行中
                instance.proxy.$mitt.emit('refreshTaskList', {}, true);
            } else {
                message.error(errorMsg);
            }
        };
        const onDrop = async (e) => {
            state.flag = false;
            if (store.getters.moveData.relateVersionNumber) {
                message.error('该需求无法绑定其他版本');
                return false;
            } else {
                if (props.detail.status === '1') {
                    handleUpdateBatch();
                } else {
                    if (!state.processStepStatus) {
                        await getProcessStatus();
                    }
                    if (['productChange', 'basicLine'].includes(state.processStepStatus)) {
                        handleUpdateBatch();
                    } else {
                        message.error('该流程下不能添加需求');
                    }
                }
            }
        };
        const handleShow = (ev) => {
            ev.preventDefault();
            state.lastenter = ev.target;
            activeKey.value = ['1'];
            state.flag = true;
        };
        const handleHide = (ev) => {
            if (state.lastenter === ev.target) {
                state.flag = false;
                ev.stopPropagation();
                ev.preventDefault();
            }
        };
        const showDetail = () => {
            router.push({
                path: '/version/versionDetail',
                query: {
                    id: props.detail.id
                }
            });
        };
        const showProDetail = (id) => {
            router.push({
                path: '/productRequire/productDetail',
                query: {
                    id
                }
            });
        };
        const getProcessStatus = async () => {
            const query = {
                instanceId: props.detail.instanceId
            };
            const { success, moule } = await api.productProcessModel.processStatus(query);
            if (success) {
                state.processStepStatus = moule;
            }
            return success;
        };
        onMounted(() => {
            useDrop(unref(versionItemRef), {
                onShow: handleShow,
                onHide: handleHide,
                onDrop
            });
        });

        return {
            ...toRefs(state),
            productTableColumns,
            versionItemRef,
            requireListRef,
            OpinionModalRef,
            activeKey,
            customStyle,
            handleChange,
            rangeTime,
            showDetail,
            showProDetail,
            handleOpinionModalSuccess,
            handleDelete
        };
    }
});
</script>
<style lang="less">
.ant-collapse > .ant-collapse-item > .ant-collapse-header {
    display: flex;
    align-items: center;
    .ant-collapse-extra {
        float: none;
        flex: 1;
    }
}
</style>
<style scoped lang="less">
::v-deep(.ant-collapse > .ant-collapse-item > .ant-collapse-header) {
    padding: 5px 16px;
    padding-left: 40px;
}
.flag {
    ::v-deep(.ant-collapse-header) {
        border: 1px dashed @primary-color;
    }
}
.section-wrap {
    .section-cont {
        padding: 0 12px;
    }

    .section-header {
        height: 40px;
        margin-bottom: 12px;
        &-title {
            font-size: 14px;
            color: @title-font-color;
            font-weight: bold;
        }
        &-action {
            flex: 1;
        }
    }

    .pro-num-wrap {
        display: flex;
        align-items: center;
        padding: 2px;
        margin-left: 8px;
        border-radius: 13px;
        border: 1px solid #d9d9d9;
        font-size: 12px;
        .title {
            font-size: 12px;
            line-height: 12px;
            margin: 0 2px;
            color: #505a6e;
        }
    }

    .btn-cont {
        margin-left: 8px;
        width: 92px;
        padding: 0 6px;
        height: 32px;
        border-radius: 4px;
        background: rgba(23, 35, 61, 0.05);
    }
}
</style>